//
//  CTPComposeViewController.m
//  LittleNotes
//
//  Created by 檀志文 on 16/5/19.
//  Copyright © 2016年 ios檀志文. All rights reserved.
//

#import "CTPComposeViewController.h"
#import "CTPPlaceholderTextView.h"
#import <Masonry.h>
#import "UIBarButtonItem+Extension.h"
#import "CTPPhoneSelectorController.h"
#import "MBProgressHUD+PKX.h"
#import "CTPMsgViewModel.h"
#import "CTPMessage.h"
#import <sqlite3.h>

static NSInteger maxOfLength = 25;

@interface CTPComposeViewController ()<UITextViewDelegate>


@property (nonatomic, strong) CTPPlaceholderTextView *textView;

// 自定义toolBar
@property (nonatomic, strong) UIToolbar *toolBar;

// 照片的view是否显示
@property (nonatomic, assign) BOOL isShowPhotoSelectorView;
// 图片选择控制器
@property (nonatomic, strong) CTPPhoneSelectorController *photoSelectorVC;

// 自定义的一个uilabel
@property (nonatomic, strong) UILabel *lengthTipLabel;

@end

@implementation CTPComposeViewController


-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (self.isShowPhotoSelectorView) {
        [self.textView becomeFirstResponder];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
        self.view.backgroundColor = [UIColor whiteColor];
    [self textView];
    [self toolBar];
    [self prepareUI];
    // 监听键盘frame的改变
    //
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

// 监听键盘的改变
-(void)willChangeFrame:(NSNotification *)notification{
    CGRect frame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
    CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    CGFloat y = frame.origin.y - [UIScreen mainScreen].bounds.size.height;
    //    // 动画
    [_toolBar mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(y);
    }];
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
    
}
// 移除通知
- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark  自定义toolbar中的问题点击响应事件

-(void) picture{
    self.isShowPhotoSelectorView = YES;
    [self.photoSelectorVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(0);
    }];
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
    //  让键盘退下
    [self.textView resignFirstResponder];
}

-(void)del{
//
//    self.isShowPhotoSelectorView = NO;
    //  让键盘退下
    [self.textView resignFirstResponder];
}


-(void) setupToolBar{
    // 每个item对应的图片名称
    [_toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
    
    NSMutableArray *arrayM1 = @[@{@"imageName": @"compose_toolbar_picture",@"action": @"picture"},@{@"imageName": @"compose_emotion_delete",@"action": @"del"}];
    
    NSMutableArray *items = [NSMutableArray array];
    [arrayM1 enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *imageName =  obj[@"imageName"];
        NSString *action1 = obj[@"action"];
        
        UIBarButtonItem *item = [[UIBarButtonItem alloc]init:imageName target:self action:NSSelectorFromString(action1)];
        UIButton *btn = [item customView];
        btn.tag = idx;
        [items addObject:item];
        
        UIBarButtonItem *flexibleBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        [items addObject:flexibleBtn];
    }];
    [items removeLastObject];
    _toolBar.items = items;
}

-(void) setupNavigationBar{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(closed)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(sendMsgs)];
    [self setupTitleView];
}

/// 设置TitleView
-(void) setupTitleView{
        NSString *prefix = @"记录笔记";
        NSString *name = @"123";
        NSString *title = [NSString stringWithFormat:@"%@\n%@",prefix,name];
        UILabel *titleLabel = [[UILabel alloc]init];
        titleLabel.numberOfLines = 0;
        titleLabel.textAlignment =NSTextAlignmentCenter;
        titleLabel.textColor = [UIColor blackColor];
        titleLabel.font = [UIFont systemFontOfSize:14];
        //        属性文本
        NSMutableAttributedString *attStringM = [[NSMutableAttributedString alloc]initWithString:title];
        NSRange range = [title rangeOfString:name];
        [attStringM addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:range];
        [attStringM addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:range];
        titleLabel.attributedText = attStringM;
        [titleLabel sizeToFit];
        self.navigationItem.titleView = titleLabel;
        self.navigationItem.title = prefix;
}
// 取消
-(void)closed{
    // textView取消第一相应者,键盘就会退下
    [_textView resignFirstResponder];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

// 发送
-(void)sendMsgs{
    NSString *text = self.textView.text;
    // 判断是否超出了长度
    NSInteger last=maxOfLength-text.length;
    if (last<0) {
        [MBProgressHUD showError:@"超出最大长度"];
        return;
    }
    // 提示正在发微博
    [MBProgressHUD showMessage:@"正在发布..."];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 隐藏登录指示器
        [MBProgressHUD hideHUD];
        // 提示登录成功
        [MBProgressHUD showSuccess:@"发布成功"];
        // 去照片选择器里面拿图片
        
#pragma 只是选取一张的时候 NSString *randomImageName
        
        UIImage *image= self.photoSelectorVC.photos.firstObject;
        
        NSMutableArray *imagearr = [[NSMutableArray alloc] init];
//        
            NSString *randomImageName = [NSString stringWithFormat:@"%zd",arc4random_uniform(100)];
        if (image) {
        
//            NSString *filePath =  [sandBoxPath stringByAppendingPathComponent:@"/image/png"];
            NSString *imagePath =[sandBoxPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@%@",randomImageName,@".png"]];
            [imagearr addObject:image];
//
            [UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
//            [image wri]
        }
        
        //获得系统时间
        NSDate *  senddate=[NSDate date];
        NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"HH:mm:ss"];
        NSString *  locationString=[dateformatter stringFromDate:senddate];
        //获得系统日期
        NSCalendar  * cal=[NSCalendar  currentCalendar];
        NSUInteger  unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
        NSDateComponents * conponent= [cal components:unitFlags fromDate:senddate];
        NSInteger year=[conponent year];
        NSInteger month=[conponent month];
        NSInteger day=[conponent day];
#warning 存放到数据库中的日期格式定死为2014/08/12 00:00:00
//        NSString *nsDateString= [NSString  stringWithFormat:@"%4ld年%2ld月%2ld日%@",year,month,day,locationString];
        NSString *nsDateString= [NSString  stringWithFormat:@"%4ld/%2ld/%2ld %@",year,month,day,locationString];
        NSString *imageName = [NSString stringWithFormat:@"%@",nsDateString];
        
#warning  发送说说的回调方法
        CTPMessage *message =[[CTPMessage alloc]initWithTitleId:1 content:text created_at:imageName pic_urls:randomImageName];
        [[CTPMsgViewModel sharedMsgInstance]insertMsgs:message];
//      返回到列表
        [self.navigationController popToRootViewControllerAnimated:YES];
    });
}

-(void) prepareUI{
    [self setupNavigationBar];
    [self setupTextView];
//  设置照片选择器的view
    [self setupPhotoSelectorView];
    [self setupToolBar];
    [self setupLengthTipLabel];
}
-(void) setupLengthTipLabel{
    [self.view addSubview:self.lengthTipLabel];
    [self.lengthTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.toolBar.mas_top).offset(-4);
        make.trailing.equalTo(self.toolBar).offset(-4);
    }];
}

//将照片选择控制器的view添加到发微博控制器的view里面
-(void) setupPhotoSelectorView{
//   设置照片选择控制器
    UIView *photoSelectorView =self.photoSelectorVC.view;
    [self.view addSubview:photoSelectorView];
    // 当一个控制器的view成为另一个控制器的view的子view,那么这个控制器页最好成为另外一个控制器的子控制器
    [self addChildViewController:self.photoSelectorVC];
    //  添加约束
    [photoSelectorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.bottom.equalTo(self.view).offset([UIScreen mainScreen].bounds.size.height * 0.6);
        make.height.mas_equalTo([UIScreen mainScreen].bounds.size.width * 0.6);
    }];
}

-(void) setupTextView{
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

#pragma mark - 懒加载
- (CTPPhoneSelectorController *)photoSelectorVC{
    if (_photoSelectorVC==nil) {
        _photoSelectorVC = [[CTPPhoneSelectorController alloc]init];
    }
    return _photoSelectorVC;
}

- (UILabel *)lengthTipLabel{
    if (_lengthTipLabel==nil) {
        _lengthTipLabel = [[UILabel alloc]init];
        _lengthTipLabel.font = [UIFont systemFontOfSize:10];
        _lengthTipLabel.text= [NSString stringWithFormat:@"%ld",maxOfLength];
        [_lengthTipLabel sizeToFit];
    }
    return _lengthTipLabel;
}
- (CTPPlaceholderTextView *)textView{
    if (_textView == nil) {
        CTPPlaceholderTextView *tv = [[CTPPlaceholderTextView alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width*0.5, [UIScreen mainScreen].bounds.size.height*0.5)];
        tv.font = [UIFont systemFontOfSize:14];
        [tv setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg4.jpg"]]];
        tv.textColor = [UIColor grayColor];
        tv.text = @"写点什么吧......";
        self.textView = tv;
        [self.view addSubview:tv];
    
        //监听textView文字的改变
        tv.delegate = self;
        //垂直弹簧效果
        tv.alwaysBounceVertical = YES;
        //当拖拽textView就会关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    }
    return _textView;
}

- (UIToolbar *)toolBar{
    if (_toolBar ==nil) {
        UIToolbar *toolBar = [[UIToolbar alloc]init];
        [self.view addSubview:toolBar];
        _toolBar = toolBar;
    }
    return _toolBar;
}

#pragma mark -textview 的代理方法
-(void) textViewDidChange:(UITextView *)textView{
    self.navigationItem.rightBarButtonItem.enabled =[textView hasText];
//  已经输入文本
    NSString *text = self.textView.text;
    // 计算剩余文本的长度
    NSInteger last = maxOfLength - text.length;
    self.lengthTipLabel.text = [NSString stringWithFormat:@"%ld",last];
    UIColor *color =  last<0 ? [UIColor redColor]:[UIColor lightGrayColor];
    self.lengthTipLabel.textColor = color;
}

@end
